/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.tbp.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

/**
 *
 * @author Diego
 */
public class DiasUteis {

    public static Date stringToDate(String stringDate) {

        Date date = null;

        try {
            SimpleDateFormat sdf =
                    new SimpleDateFormat("dd/MM/yyyy", new Locale("pt_BR"));
            date = sdf.parse(stringDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return date;
    }

    public static int deductDates(Date initialDate, Date finalDate) {

        if (initialDate == null || finalDate == null) {
            return 0;
        }

        int days = (int) ((finalDate.getTime() - initialDate.getTime()) / (24 * 60 * 60 * 1000));


        return (days > 0 ? days : 0);
    }

    public static String dateToString(Date date) {

        SimpleDateFormat sdf =
                new SimpleDateFormat("dd/MM/yyyy", new Locale("pt_BR"));
        String dateFormated = sdf.format(date);

        return dateFormated;
    }

    public static Date clearHour(Date date) {
        return (stringToDate(dateToString(date)));
    }

    public static int getWorkingDays(Date initialDate, Date finalDate) {

        int workingDays = 0;
        int totalDays = deductDates(initialDate, finalDate);

        Calendar calendar = new GregorianCalendar();

        //Setando o calendar com a Data Inicial
        calendar.setTime(initialDate);

        for (int i = 0; i <= totalDays; i++) {

            if (!(calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) && !(calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)) {
                workingDays++;
            }
            calendar.add(Calendar.DATE, 1);

        }
        return workingDays;
    }
}
